import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.rabbitmq.*;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
import com.herohead.*;

/*
 * This program will read the message queue and update MYSQL database.
 * 
 * 
 */


public class upsertAVGC {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws InterruptedException 
	 * @throws RuntimeException 
	 * @throws ShutdownSignalException 
	 */

	private static org.apache.log4j.Logger log= Logger.getLogger(upsertAVGC.class);

	public static PreparedStatement upsert = null;
	private static Statement statement = null;
	private static Connection connect = null;
	//private static ResultSet resultSet = null;
	private static String serverName = null;
	private static String queue = null;

	static Channel channel;

	public static void main(String[] args) throws IOException, ShutdownSignalException, RuntimeException, InterruptedException, SQLException {
		// TODO Auto-generated method stub

		Misc m = new Misc();

		queue = args[0];
		serverName = args[1];

		String mysqlserverConnectString = "jdbc:mysql://us01s-netops01.am.mt.mtnet?user=backup&password=networker";

		PropertyConfigurator.configure("upsertAVGC.prop");
		// Log info about the environment.

		log.info("Program started");
		log.debug("Java version =" + m.getSystemInfoJavaVersion());
		log.debug("LocalHost = " + m.getSystemLocalHostName());
		final int numberOfRetries = 10 ;
		final long timeToWait = 30000 ;

		Connection connection = null;
		
		for (int i=1; i<numberOfRetries; i++) {

			try {
		connect = DriverManager.getConnection(mysqlserverConnectString);
		break ;
	}
	catch (Exception e) {
		try {
			System. out .println("Trying to connect to " + mysqlserverConnectString + " - try " + i + " of " + numberOfRetries + " - retry in 30 secs" );
			Thread. sleep(timeToWait);
		}
		catch (InterruptedException e1) {
		}
	}
}
		
		statement = connect.createStatement();

		upsert = connect.prepareStatement("insert into backup.avamar_gc (date,new_data,bu,removed_data,gc,net_change,server,added) values (?,?,?,?,?,?,?,?) on DUPLICATE KEY UPDATE date=?,new_data=?,bu=?,removed_data=?,gc=?,net_change=?,server=?,added=?");

		Rabbitmq rmq = new Rabbitmq();

		rmq.setHostname("us01s-netops01.am.mt.mtnet");
		rmq.setLogin("backup", "networker", "backup");
		rmq.setupChannel();
		rmq.setQueue(queue);
		rmq.declareQue();
		channel = rmq.getChannel();
		QueueingConsumer consumer = new QueueingConsumer(channel);

		channel.basicConsume(rmq.getQueue(), true, consumer);

		channel = rmq.getChannel();
		System.out.println("Waiting for message");
		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			SplitMessage(message);
			//			System.out.println(message);
			log.debug("Found message - " + message);
		}
	}

	public static void SplitMessage(String message) throws SQLException {

		connect = DriverManager.getConnection("jdbc:mysql://us01s-netops01.am.mt.mtnet?user=backup&password=networker");
		statement = connect.createStatement();
		upsert = connect.prepareStatement("insert into backup.avamar_gc (date,new_data,bu,removed_data,gc,net_change,server,added) values (?,?,?,?,?,?,?,?) on DUPLICATE KEY UPDATE date=?,new_data=?,bu=?,removed_data=?,gc=?,net_change=?,server=?,added=?");

		log.debug("Splitting messaging");

		String date = message.substring(0, 10);

		//System.out.println("new_data");

		String nd = (String) message.subSequence(11, 20);
		nd = nd.trim();
		if (nd.isEmpty()) {nd = "0";}
		String new_data = nd;

		//System.out.println("bu");
		String b = (String) message.subSequence(23, 28);
		b = b.trim();
		if (b.isEmpty()) {b = "0";}
		String bu = b;

		//System.out.println("removed_data");
		String rd =(String) message.subSequence(29, 38);
		rd = rd.trim();
		if (rd.isEmpty()) {rd = "0";}
		String remove_data = rd;

		//System.out.println("gc");
		String g = (String) message.subSequence(41, 43);
		g = g.trim();
		if (g.isEmpty()) {g = "0";}
		String gc = g;

		//System.out.println("net_change");
		String nc = (String) message.subSequence(44, 56);
		nc = nc.trim();
		if (nc.isEmpty()) {nc = "0";}
		String net_change = nc;
		String added = Misc.getTimestamp();
//		System.out.println(Misc.getTimestamp() + " - " + date + "," + new_data + "," + bu + "," + remove_data + "," + gc + "," + net_change);

		log.debug(Misc.getTimestamp() + " - " + date + "," + new_data + "," + bu + "," + remove_data + "," + gc + "," + net_change);
		update_avamargc(upsert,date,new_data,bu,remove_data,gc,net_change,serverName,added);
		connect.close();
		log.debug("Updating database");
	}

	public static void update_avamargc(PreparedStatement upsert, String strDate, String strNew_data, String strBU, String strRemoved_data, String strstrGC, String strNetChange, String strServername, String added) throws SQLException {

		upsert.setString(1, strDate);
		upsert.setString(2, strNew_data);
		upsert.setString(3, strBU);
		upsert.setString(4, strRemoved_data);
		upsert.setString(5, strstrGC);
		upsert.setString(6, strNetChange);
		upsert.setString(7, strServername);
		upsert.setString(8, added);

		upsert.setString(9, strDate);
		upsert.setString(10, strNew_data);
		upsert.setString(11, strBU);
		upsert.setString(12, strRemoved_data);
		upsert.setString(13, strstrGC);
		upsert.setString(14, strNetChange);
		upsert.setString(15, strServername);
		upsert.setString(16, added);

		upsert.execute();

	}
}
